package com.example.libraryapp.fragment;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

import com.example.libraryapp.R;
import com.example.libraryapp.book.BookInfo;
import com.example.libraryapp.book.BookService;
import com.example.libraryapp.lend.LendService;
import com.example.libraryapp.user.UserInfo;
import com.example.libraryapp.util.Constance;
import com.example.libraryapp.util.MyConfig;

/**
 * Fragment
 */
public class FirstFragment extends Fragment implements OnQueryTextListener {

	private static Handler handler;
	private Context context;
	private SearchView svSearch;
	private ImageView ivSearch; // 搜索按钮
	private ListView lvBook;
	private BookAdapter bookAdapter;
	private List<BookInfo> bookList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (container == null) {
			return null;
		}
		View view = inflater.inflate(R.layout.first_fragment, container, false);
		findViews(view);
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getAllBookInfo(); // 得到图书信息
	}

	/**
	 * 得到所有图书信息
	 */
	private void getAllBookInfo() {
		// 清理数据库
		// BookService.clear(context);

		bookList = BookService.getAllBook(context);
		bookAdapter.setData(bookList);
		bookAdapter.notifyDataSetChanged();
	}

	/**
	 * 根据条件查询图书信息
	 * 
	 * @param param
	 */
	private void getBookInfoByParam(String param) {
		bookList = BookService.getBookInfoByParam(context, param);
	}

	/**
	 * 找到控件
	 */
	private void findViews(View view) {
		svSearch = (SearchView) view.findViewById(R.id.search_view);
		svSearch.setSubmitButtonEnabled(true);
		svSearch.setFocusable(false);
		// 为改SerchView组件设置事件监听器
		svSearch.setOnQueryTextListener(this);
		ivSearch = (ImageView) view.findViewById(R.id.iv_search);
		lvBook = (ListView) view.findViewById(R.id.lv_book);
		lvBook.setAdapter(bookAdapter);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// TODO Auto-generated method stub
		context = getActivity();
		bookAdapter = new BookAdapter(context);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {

				default:
					break;
				}
			}

		};
	}

	/**
	 * 用户单击搜索按钮时调用该方法
	 */
	@Override
	public boolean onQueryTextSubmit(String query) {
		getBookInfoByParam(query);
		bookAdapter.setData(bookList);
		bookAdapter.notifyDataSetChanged();
		return false;
	}

	/**
	 * 用户输入字符时调用该方法
	 */
	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		getBookInfoByParam(newText);
		bookAdapter.setData(bookList);
		bookAdapter.notifyDataSetChanged();
		return false;
	}

	/**
	 * 数据适配器类，给Listview填充数据
	 */
	public class BookAdapter extends BaseAdapter {
		private List<BookInfo> bookList;
		private LayoutInflater myInflater; // LayoutInfalter对象用来导入布局

		public BookAdapter(Context context) {
			this.myInflater = LayoutInflater.from(context);
		}

		public void setData(List<BookInfo> bookList) {
			this.bookList = bookList;
		}

		public int getCount() {
			if (this.bookList != null) {
				return this.bookList.size();
			}
			return 0;
		}

		public Object getItem(int paramInt) {
			return this.bookList.get(paramInt);
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		// 绘制ListItem的方法
		public View getView(final int position, View paramView,
				ViewGroup paramViewGroup) {
			View view = paramView;
			ViewHolder holder = null;

			if (paramView == null) {
				// 加载ListItem布局文件
				view = myInflater.inflate(R.layout.book_item, null);
				holder = new ViewHolder();
				// 得到各个控件的对象
				holder.ivBook = (ImageView) view.findViewById(R.id.iv_book);
				holder.tvName = (TextView) view.findViewById(R.id.tv_bookname);
				holder.tvAuthor = (TextView) view
						.findViewById(R.id.tv_bookauthor);
				holder.tvPublishing = (TextView) view
						.findViewById(R.id.tv_publishing);
				holder.bnLend = (Button) view.findViewById(R.id.bn_lend);
				// 绑定ViewHolder对象到view上
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag(); // 取出ViewHolder对象
			}
			// 得到当前ListItem需要填充的图书数据
			final BookInfo book = this.bookList.get(position);
			holder.ivBook.setBackgroundResource(book.getImageId());
			holder.tvName.setText(book.getName());
			holder.tvAuthor.setText(book.getAuthor());
			holder.tvPublishing.setText(book.getPublishing());
			holder.bnLend.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					UserInfo userInfo = MyConfig.getUserInfo(context);
					boolean alreadLend = LendService.alreadyLend(context,
							book.getId(), userInfo.getCardid());
					if (alreadLend) {
						Toast.makeText(context, "已经借了，不能重复借书！", 1).show();
						return;
					}
					new AlertDialog.Builder(context)
							.setTitle("温馨提示")
							.setMessage("首次借书时间为一个月，如果需要续借，请在借阅信息里续借？")
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialogInterface,
												int i) {

											// 借书
											boolean lendResult = LendService
													.lend(context, book);
											if (lendResult) {
												Toast.makeText(context,
														"借书成功！", 1).show();
												// 本页刷新数据
												getAllBookInfo();
												// 通知借阅页面，刷新数据
												Handler handler = SecondFragment
														.getHandler();
												if (handler != null) {
													handler.sendEmptyMessage(Constance.UPDATE_DATA);
												}
											}
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialogInterface,
												int i) {
											dialogInterface.dismiss();
										}
									}).show();
				}
			});
			// 把图书的数据设置到ListItem控件上
			return view;

		}

	}

	/**
	 * ListItem界面控件的持有类
	 */
	class ViewHolder {
		ImageView ivBook;
		TextView tvName;
		TextView tvAuthor;
		TextView tvPublishing;
		Button bnLend;
	}
}
